// pages/postDetails/index.js
Page({
    data: {
        postId: '', // 帖子ID
        post: {}, // 帖子详情
        comments: [], // 评论列表
        isLiked: false, // 帖子点赞状态
        isMyPost: false, // 是否是自己的帖子
        commentInput: '', // 评论输入内容
        userInfo: {}, // 用户信息
        currentIndex: 0,
        showDialog: false,
        beforeClose: null, // 绑定异步关闭函数
        replyContent: '', //回复内容
        commentId: 0, //回复id
        replyingToCommentId: null, // 正在回复的评论ID
        replyingToReplyId: null, // 正在回复的回复ID
        replyingToUserName: '', // 正在回复的用户名
        replyInput: '' // 回复输入内容

    },

    onLoad(options) {
        if (options.postId) {
            this.setData({
                postId: options.postId
            });
            this.getUserInfo();
            this.loadPostDetail();
            
        } else {
            wx.showToast({
                title: '参数错误',
                icon: 'none'
            });
            setTimeout(() => {
                wx.navigateBack();
            }, 1500);
        }
    },
    
    // 获取用户信息
    getUserInfo() {
        const userInfo = wx.getStorageSync('userInfo');
        if (userInfo) {
            this.setData({
                userInfo
            });
        }
    },
     // 商品详情页中点击卖家信息
     goToSellerShop: function () {
      const sellerId = this.data.post.userId;
      wx.navigateTo({
          url: `/pages/shop/shop?sellerId=${sellerId}&from=my`
      });
  },
    // 加载帖子详情
    loadPostDetail() {
        wx.showLoading({
            title: '加载中...'
        });

        wx.cloud.callFunction({
            name: 'getPostDetail',
            data: {
                postId: this.data.postId,
                userInfo: this.data.userInfo
            }
        }).then(res => {
            wx.hideLoading();
            console.log(res);
            if (res.result && res.result.success) {
                const {
                    post,
                    comments
                } = res.result.data;
                const isMyPost = post.userId === (this.data.userInfo._id || '');

                this.setData({
                    post,
                    comments,
                    isLiked: post.isLiked,
                    isMyPost,
                    currentIndex: 0
                });
            } else {
                wx.showToast({
                    title: res.result.message || '加载失败',
                    icon: 'none'
                });
                setTimeout(() => {
                    wx.navigateBack();
                }, 1500);
            }
        }).catch(err => {
            wx.hideLoading();
            console.error('加载帖子详情失败', err);
            wx.showToast({
                title: '加载失败',
                icon: 'none'
            });
        });
    },

    // 预览图片
    previewImages(e) {
        const index = e.currentTarget.dataset.index;
        const images = this.data.post.images;
        wx.previewImage({
            current: images[index],
            urls: images
        });
    },

    // 监听轮播图切换
    onSwiperChange(e) {
        this.setData({
            currentIndex: e.detail.current
        });
    },
    // 切换点赞状态
    toggleLike() {
        console.log(1);
        if (!this.data.userInfo._id) {
            wx.showModal({
                title: '提示',
                content: '请先登录',
                success: (res) => {
                    if (res.confirm) {
                        wx.navigateTo({
                            url: '/pages/login/login'
                        });
                    }
                }
            });
            return;
        }

        const isLiked = !this.data.isLiked;
        const likeCount = isLiked ? this.data.post.likeCount + 1 : this.data.post.likeCount - 1;

        wx.showLoading({
            title: '操作中...'
        });
        wx.cloud.callFunction({
            name: 'toggleLike',
            data: {
                type: 'post',
                itemId: this.data.postId,
                isLike: isLiked,
                userInfo: this.data.userInfo
            }
        }).then(res => {
            wx.hideLoading();

            if (res.result && res.result.success) {
                this.setData({
                    isLiked,
                    'post.likeCount': likeCount
                });
            } else {
                wx.showToast({
                    title: res.result.message || '操作失败',
                    icon: 'none'
                });
            }
        }).catch(err => {
            wx.hideLoading();
            console.error('点赞操作失败', err);
            wx.showToast({
                title: '操作失败',
                icon: 'none'
            });
        });
    },

    // 前往产品详情页
    goToProductDetail(e) {
        console.log(e);
        const productId = e.currentTarget.dataset.productId;
        wx.navigateTo({
            url: `/pages/products/products?productId=${productId}`
        });
    },

    // 输入评论内容
    onCommentInput(e) {
        this.setData({
            commentInput: e.detail.value
        });
    },

    // 提交评论
    submitComment() {
        const comment = this.data.commentInput.trim();
        if (!comment) {
            wx.showToast({
                title: '请输入评论内容',
                icon: 'none'
            });
            return;
        }

        if (!this.data.userInfo._id) {
            wx.showModal({
                title: '提示',
                content: '请先登录',
                success: (res) => {
                    if (res.confirm) {
                        wx.navigateTo({
                            url: '/pages/login/login'
                        });
                    }
                }
            });
            return;
        }

        wx.showLoading({
            title: '发布中...'
        });

        wx.cloud.callFunction({
            name: 'createComment',
            data: {
                postId: this.data.postId,
                content: comment,
                userId: this.data.userInfo._id,
                userName: this.data.userInfo.nickName,
                userAvatar: this.data.userInfo.avatarUrl,
            }
        }).then(res => {
            wx.hideLoading();

            if (res.result && res.result.success) {
                // 刷新评论列表
                this.loadPostDetail();
                this.setData({
                    commentInput: ''
                });
                wx.showToast({
                    title: '评论成功',
                    icon: 'none'
                });
            } else {
                wx.showToast({
                    title: res.result.message || '评论失败',
                    icon: 'none'
                });
            }
        }).catch(err => {
            wx.hideLoading();
            console.error('评论失败', err);
            wx.showToast({
                title: '评论失败',
                icon: 'none'
            });
        });
    },

    // 删除帖子
    deletePost() {
        wx.showModal({
            title: '确认删除',
            content: '确定要删除这个帖子吗？删除后不可恢复',
            success: (res) => {
                if (res.confirm) {
                    this.deletePostFromServer();
                }
            }
        });
    },

    // 从服务器删除帖子
    deletePostFromServer() {
        wx.showLoading({
            title: '删除中...'
        });

        wx.cloud.callFunction({
            name: 'deletePost',
            data: {
                postId: this.data.postId,
                userInfo:this.data.userInfo
            }
        }).then(res => {
            wx.hideLoading();
            console.log(res);
            if (res.result && res.result.success) {
                wx.showToast({
                    title: '删除成功',
                    icon: 'none'
                });
                setTimeout(() => {
                    wx.navigateBack();
                }, 1500);
            } else {
                wx.showToast({
                    title: res.result.message || '删除失败',
                    icon: 'none'
                });
            }
        }).catch(err => {
            wx.hideLoading();
            console.error('删除帖子失败', err);
            wx.showToast({
                title: '删除失败',
                icon: 'none'
            });
        });
    },
    // 回复评论
    replyComment(e) {
        console.log(e);
        const commentId = e.currentTarget.dataset.commentId;
        const comment = this.findCommentById(commentId);
        console.log(comment);
        if (comment) {
            this.setData({
                replyingToCommentId: commentId,
                replyingToReplyId: null,
                replyingToUserName: comment.userName,
                replyInput: ''
            });
        }
    },

    // 回复回复
    replyReply(e) {
        console.log(e);
        const commentId = e.currentTarget.dataset.commentId;
        const replyId = e.currentTarget.dataset.replyId;
        const comment = this.findCommentById(commentId);
        const reply = this.findReplyInComment(comment, replyId);
        console.log(comment);
        console.log(reply);
        if (comment && reply) {
            this.setData({
                replyingToCommentId: commentId,
                replyingToReplyId: replyId,
                replyingToUserName: reply.userName,
                replyInput: ''
            });
        }
    },
    // 输入回复内容
    onReplyInput(e) {
        this.setData({
            replyInput: e.detail.value
        });
    },
    // 提交回复
    submitReply() {
        const {
            replyingToCommentId,
            replyingToReplyId,
            replyingToUserName,
            replyInput,
            userInfo
        } = this.data;
        const content = replyInput.trim();

        if (!content) {
            wx.showToast({
                title: '请输入回复内容',
                icon: 'none'
            });
            return;
        }

        wx.showLoading({
            title: '发表中...'
        });

        wx.cloud.callFunction({
            name: 'createComment',
            data: {
                postId: this.data.postId,
                userId: userInfo._id,
                userName: userInfo.nickName,
                userAvatar: userInfo.avatarUrl,
                content,
                replyTo: replyingToReplyId || replyingToCommentId,
                replyToUser: replyingToUserName
            },
            success: res => {
                wx.hideLoading();

                if (res.result && res.result.success) {
                    // 刷新评论列表
                    this.loadPostDetail();

                    // 清空回复状态
                    this.setData({
                        replyingToCommentId: null,
                        replyingToReplyId: null,
                        replyingToUserName: '',
                        replyInput: ''
                    });

                    wx.showToast({
                        title: '回复成功',
                        icon: 'success'
                    });
                } else {
                    wx.showToast({
                        title: res.result.message || '回复失败',
                        icon: 'none'
                    });
                }
            },
            fail: err => {
                wx.hideLoading();
                console.error('回复失败', err);
                wx.showToast({
                    title: '回复失败',
                    icon: 'none'
                });
            }
        });
    },
    // 根据ID查找评论
    findCommentById(commentId) {
        const {
            comments
        } = this.data;
        for (const comment of comments) {
            if (comment._id === commentId) {
                return comment;
            }
            if (comment.replies && comment.replies.length > 0) {
                const reply = this.findReplyInComment(comment, commentId);
                if (reply) return reply;
            }
        }
        return null;
    },

    // 在评论中查找回复
    findReplyInComment(comment, replyId) {
        for (const reply of comment.replies) {
            if (reply._id === replyId) {
                return reply;
            }
            if (reply.replies && reply.replies.length > 0) {
                const nestedReply = this.findReplyInComment(reply, replyId);
                if (nestedReply) return nestedReply;
            }
        }
        return null;
    },
    // 切换评论点赞状态
    toggleCommentLike(e) {
        console.log(this.data.comments);
        console.log(e);
        const commentId = e.currentTarget.dataset.commentId;
        let arr = this.data.comments.filter(item=>{
            return item._id == commentId
        })
        let isLiked = !arr[0].isLiked
        const likeCount = isLiked ? arr[0].likeCount + 1 : arr[0].likeCount - 1;
        this.toggleLike2('comment', commentId,isLiked);
    },

    // 切换回复点赞状态
    toggleReplyLike(e) {
        console.log(e);
        console.log(this.data.comments);
        const {
            commentId,
            replyId
        } = e.currentTarget.dataset;
        let cArr = this.data.comments.filter(item=>{
            return item._id == commentId
        })
        console.log(cArr);
        let rArr = cArr[0].replies.filter(item=>{
            return item._id == replyId
        })
        console.log(rArr);
        let isLiked = !rArr[0].isLiked
        const likeCount = isLiked ? rArr[0].likeCount + 1 : rArr[0].likeCount - 1;
        this.toggleLike2('comment', replyId,isLiked);
    },

    // 切换点赞状态
    toggleLike2(type, itemId,isLiked) {
        const {
            userInfo
        } = this.data;

        if (!userInfo._id) {
            wx.showToast({
                title: '请先登录',
                icon: 'none'
            });
            return;
        }

        wx.cloud.callFunction({
            name: 'toggleLike',
            data: {
                type,
                itemId,
                isLike: isLiked,
                userInfo: this.data.userInfo
            },
            success: res => {
                if (res.result && res.result.success) {
                    this.loadPostDetail();
                    wx.showToast({
                        title: res.result.isLiked ? '取消点赞' : '点赞成功',
                        icon: 'success'
                    });
                } else {
                    wx.showToast({
                        title: res.result.message || '操作失败',
                        icon: 'none'
                    });
                }
            },
            fail: err => {
                console.error('点赞操作失败', err);
                wx.showToast({
                    title: '操作失败',
                    icon: 'none'
                });
            }
        });
    },
});